package FenxiaoService

import (
	"gdshop-admin-go-api/app/request/BaseReq"
	"gdshop-admin-go-api/app/service/CategoryService"
	"gdshop-admin-go-api/app/service/GoodsService"
	"gdshop-admin-go-api/library/response"
	"gdshop-admin-go-api/library/tools"
	toolsDb "gdshop-admin-go-api/library/tools/db"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/util/gconv"
)

func GetGoodsPage(r *ghttp.Request, req *BaseReq.I) *response.JsonResponse {
	ctx := r.GetCtx()
	userWhere := g.Map{}
	keyWord := r.GetString("keyWord", "")
	categoryId := r.GetInt("category_id", 0)
	if categoryId > 0 {
		userWhere["g.cates LIKE ?"] = "%," + gconv.String(categoryId) + ",%"
	}
	if keyWord != "" {
		userWhere["g.goods_name LIKE ?"] = "%" + keyWord + "%"
	}
	obj := toolsDb.GetUnSafaTable(ctx, "fenxiao_goods").As("fg").LeftJoin("goods g", "fg.goods_id = g.id").
		LeftJoin("fenxiao_goods_level fgl", "fg.id = fgl.fenxiao_goods_id").
		Fields("fg.id AS fg_id,fg.status AS fg_status,fgl.one_rate,fgl.two_rate,fgl.three_rate,g.*").Where("fg.delete_at<1 AND g.delete_at<1").
		Order("g.display_sort DESC,g.update_at DESC,g.id DESC").Where(userWhere)

	res, err := obj.Page(req.Page, req.PageSize).All()
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}
	count, err := obj.Fields("1").Count()
	if err != nil {
		return response.FailByRequestMessage(r, err.Error())
	}

	resList := res.List()
	// 先取出分类
	cateArr, err := CategoryService.GetCategoryArrayType(ctx, "shop")
	if err != nil {
		return response.FailByRequestMessage(nil, err.Error())
	}
	resList = GoodsService.GoodsPageHandle(cateArr, resList)

	return response.SuccessByRequestMessageData(nil, "获取成功",
		g.Map{
			"list":       resList,
			"pagination": tools.GetPageInfo(count, req.Page, req.PageSize),
		})
}
